// pages/goods/list/index.js
import {
  reqGoodsPageData
} from '../../../api/goods'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [], // 商品列表数据
    isFinish: false, // 判断数据是否加载完毕
    page: 1,
    limit: 10,
    total: 0,
    routeParam: {},
    loading: true,
    isLoading: false
  },
  onLoad(options) {
    this.setData({
      routeParam: options
    })
    this.initData(options)
  },
  async initData(options) {
    this.data.isLoading = true
    const reqParams = {
      ...options,
      page: this.data.page,
      limit: this.data.limit
    }
    console.log(reqParams, 'reqParams');
    const res = await reqGoodsPageData(reqParams)
    if (res.code === 200) {
      this.setData({
        goodsList: [...this.data.goodsList, ...res.data.records],
        total: res.data.total,
        loading: false
      })
      this.data.isLoading = false
    }
  },
  gotoBack() {
    wx.navigateBack({
      delta: 1,
    })
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.data.total === this.data.goodsList.length) {
      this.setData({
        isFinish: true
      })
      return
    }
    // 判断是否加载完毕，如果 isLoading 等于 true
    // 说明数据还没有加载完毕，不加载下一页数据
    if (this.data.isLoading) return
    this.setData({
      page: this.data.page + 1,
    })
    this.initData(this.data.routeParam)
  },
  // 下拉刷新
  onPullDownRefresh() {
    // 重置数据
    this.setData({
      goodsList: [], // 商品列表数据
      isFinish: false, // 判断数据是否加载完毕
      page: 1,
      limit: 10,
      total: 0,
      loading: true
    })
    // 重新发送请求
    this.initData(this.data.routeParam)
    // 停止下拉刷新
    wx.stopPullDownRefresh()
    // 提示信息
    wx.flowerTipToast({
      title: '刷新成功',
      icon: 'success'
    })
  }
})